package cn.kgc.springmvc.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: mosin
 * @version: v1.0  2022/5/6
 *拦截非法的登录请求
 */
public class LoginInterceptor implements HandlerInterceptor {

    //前端请求到达controller之前
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return   false  拦截   true  放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求被拦截");
        //获取请求路径
        String requestURI = request.getRequestURI();  // /mvc/user/login
       if(requestURI.endsWith("login")||requestURI.endsWith("register")){
            return true;
       }

       //获取session中的user
        Object user = request.getSession().getAttribute("user");
        if(user!=null){  // 已经登录
            return  true;
        }else{ // 跳转登录页
            response.sendRedirect(request.getContextPath()+"/static/login.jsp");
        }
        return false;
    }
}
